<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-07
 * Time: 09:42
 */

namespace app\services;


use app\models\Linkers;

class LinkerService extends ServiceBase
{
    /**
     * @return Linkers[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAll($appletId)
    {
        $linkers = Linkers::where(['appletId' => $appletId])->order(['sort' => 'desc'])->select();

        return $linkers;
    }

    /**
     * @param array $params
     * @param int $page
     * @param int $pagesize
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($params=[], $page=1, $pagesize=10)
    {
        return Linkers::lists($params, $page, $pagesize);
    }

    /**
     * @param $id
     * @return Linkers|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail($id)
    {
        $linkers = Linkers::find($id);

        if ($linkers instanceof Linkers) {
            return $linkers;
        }

        throw new \Exception('链接不存在');
    }

    /**
     * 添加组织
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function add($params)
    {
        try {
            $linker = new Linkers();

            foreach ($params as $key => $val) {
                $linker->$key = $val;
            }
            $linker->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * 更新组织
     * @param Linkers $linker
     * @param $params
     */
    public function update(Linkers $linker, $params)
    {
        foreach ($params as $key => $val) {
            $linker->$key = $val;
        }
        $linker->save();
    }

    /**
     * 上架组织
     * @param Linkers $linker
     */
    public function enable(Linkers $linker)
    {
        $linker->status = 1;
        $linker->save();
    }

    /**
     * 下架组织
     * @param Linkers $linker
     */
    public function disable(Linkers $linker)
    {
        $linker->status = 0;
        $linker->save();
    }
}